我們接著加入完成功能
index.tsx
import { useEffect, useState } from "react";
import { invoke } from '@tauri-apps/api/tauri';
const itemStyle = {
padding: '8px',
};
interface Todo {
id: number,
title: string,
date: string,
done: boolean
}
function App() {
const [todos, setTodos] = useState<Todo[]>([]);
const [todo, setTodo] = useState<Todo>({id: -1, title: "", date: "None", done: false});
useEffect(()=> {
fetchAllTodo();
}, [todos]);
const fetchAllTodo = async () => {
setTodos(await invoke("get_todos"));
}
const handleTitleChange = (e: React.FormEvent<HTMLInputElement>) => {
let value = e.currentTarget.value;
setTodo({...todo, title: value});
}
const handleTodoAdd = async () => {
await invoke("new_todo", { title: todo.title, date: Date.now.toString() });
setTodo({...todo, title: ""});
}
const handleTodoDelete = async (id: number) => {
console.log(id);
await invoke("delete_todo", { id: id});
setTodo({...todo, title: ""});
}
const handleChecked = async (index: number) => {
await invoke("done_todo", {id : todos[index].id});
}
return (
<div className="container">
<h1>Welcome to Todo List</h1>
<div className="row">
<input
id="greet-input"
onChange={(e) => handleTitleChange(e)}
placeholder="Enter a task..."
value={todo.title}
/>
<button type="button" onClick={() => handleTodoAdd()}>
Add
</button>
</div>
<hr />
{todos.map((todo, index) => {
return (
<div className="row" key={index}>
<div style={itemStyle}></div>
<span
onClick={() => handleChecked(index)}
style={{
textDecoration: todos[index].done && 'line-through',
}}
>
{todo.title}
</span>
<button type="button" onClick={() => handleTodoDelete(todo.id)}>
Delete
</button>
</div>
);
})}
</div>
);
}
export default App;
const handleChecked = async (index: number) => {
await invoke("done_todo", {id : todos[index].id});
}
return (
<div className="row" key={index}>
<div style={itemStyle}></div>
<span
onClick={() => handleChecked(index)}
style={{
textDecoration: todos[index].done && 'line-through',
}}
>
{todo.title}
</span>
<button type="button" onClick={() => handleTodoDelete(todo.id)}>
Delete
</button>
</div>
);
接著,我們進行測試
發現他被劃掉了,接著我們去db看,也能發現他被修改了
而這裡有個問題,當你再點一次時,不會變成undone,我們修改一下,回到我們的todo.rs裡的done_todo
pub fn done_todo(&self, id: i32) -> bool {
match self
.conn
.execute("UPDATE Todo SET done=1 WHERE id=$1 AND done=0", [id])
{
Ok(done) => {
if done==0 {
match self
.conn
.execute("UPDATE Todo SET done=0 WHERE id=$1 AND done=1", [id])
{
Ok(undone) => {
println!("{} undone", undone);
}
Err(err) => {
println!("Undone Error: {}", err);
}
}
}
println!("{} done", done);
true
}
Err(err) => {
println!("Done Error: {}", err);
false
}
}
}
接著,我們來測試一下,執行pnpm tauri dev
我們發現點擊我們的title會將其設為done並劃掉,此時如果再點一次,就能設為not done的狀態